#!/usr/bin/env python
# coding: utf-8
# @Time   : 2022/11/25 11:24
# @Author : 梁灿

from selenium import webdriver
from py.xml import html
from datetime import datetime

driver = webdriver
import pytest
import uiautomator2 as u2

d = u2.connect()


@pytest.fixture(scope='session')  # 以实现多个.py跨文件使用一个session来完成多个用例
def login():
    d(text="StarKard").click()
    # 登录
    # 点击个人中心
    d.xpath('//*[@resource-id="com.pivite.starkard:id/content_frame"]/'
            'android.widget.RelativeLayout[1]/androidx.appcompat.widget.LinearLayoutCompat[1]/'
            'android.widget.LinearLayout[5]/android.widget.LinearLayout[1]/android.widget.ImageView[1]').click()
    # 获取文本
    element = d(resourceId="com.pivite.starkard:id/tv_name")
    ele = element.get_text()
    print(ele)
    if ele == '未登录':
        d(resourceId="com.pivite.starkard:id/tv_name").click()
        # 密码登录
        d(resourceId="com.pivite.starkard:id/et_text", text="输入手机号").click()
        d.send_keys("18875272518", clear=True)
        d(resourceId="com.pivite.starkard:id/et_text", text="输入密码").click()
        d.send_keys("123456", clear=True)
        # 点击登录
        d(resourceId="com.pivite.starkard:id/tv_login").click()


@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item):
    """当测试失败的时候，自动截图"""
    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()
    report.description = str(item.function.__doc__)
    extra = getattr(report, 'extra', [])


def pytest_html_report_title(report):
    report.title = "球星卡APP测试报告"


def pytest_configure(config):
    # config._metadata.clear()  # 清空原先Environment中的内容
    config._metadata['测试项目'] = "球星卡项目"
    config._metadata['测试地址'] = "http: //qxk.admin.sauou.com/"


def pytest_html_results_summary(prefix, summary, postfix):
    # prefix.clear() # 清空summary中的内容
    prefix.extend([html.p("所属部门: 重庆派维特公司测试部")])
    prefix.extend([html.p("测试执行人: 梁灿")])


def pytest_html_results_table_header(cells):
    cells.insert(1, html.th('测试标题'))
    cells.insert(2, html.th('测试描述'))
    cells.pop(2)  # 将原有的test删除


def pytest_html_results_table_row(report, cells):
    cells.insert(2, html.td(report.description))
    cells.insert(3, html.td(datetime.utcnow(), class_='col-time'))
    # cells.insert(1,html.td(report.nodeid))
    cells.pop()


def pytest_html_results_table_html(report, data):
    if report.passed:
        del data[:]
        data.append(html.div('通过的用例未捕捉日志输出', class_ ='empty.log'))


def _capture_screenshot():
    """截图保存未base64"""
    return driver.get_screenshot_as_base64()